package com.zdj.presentation.modules.login.vms;

import android.databinding.ObservableField;

import com.zdj.data.entity.Login;
import com.zdj.data.net.DefaultSubscribe;
import com.zdj.data.net.NetWorks;
import com.zdj.presentation.base.BaseViewModel;
import com.zdj.presentation.modules.login.handlers.LoginHandler;
import com.zdj.presentation.modules.login.models.LoginModel;
import com.zdj.presentation.modules.login.views.LoginActivity;
import com.zdj.utils.MyLogUtil;

import java.io.IOException;

import retrofit2.Response;
import retrofit2.adapter.rxjava.Result;

/**
 * Created by zdj on 16-6-16.
 */

public class LoginVm extends BaseViewModel<LoginActivity> implements LoginHandler{

    public final ObservableField<LoginModel> loginModel = new ObservableField<>();

    public LoginVm(LoginActivity loginActivity) {
        super(loginActivity);
        loginModel.set(new LoginModel());
    }


    @Override
    public void onLoginClick() {
        NetWorks.login(loginModel.get().username, loginModel.get().password, new DefaultSubscribe<Result<Login>>() {
            @Override
            public void onCompleted() {
                super.onCompleted();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(Result<Login> loginResult) {
                super.onNext(loginResult);
                Response<Login> response = loginResult.response();
                if(response.isSuccessful()){
                    MyLogUtil.e(TAG, "onNext: " + response.body());
                }else{
                    try {
                        t.showToast(response.errorBody().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
